<script setup lang="ts">
import { defineProps, defineEmits } from 'vue'
import * as XLSX from 'xlsx'
import {ElMessage} from "element-plus";

// 定义 props
const props = defineProps<{
  fields: string[] // 导入字段列表（已排除 assignment_id）
}>()

// 定义 emit
const emit = defineEmits<{
  (e: 'import-data', data: Record<string, any>[]): void
}>()

// 白名单时间字段
const dateFields = [
  'planned_start_time',
  'planned_end_time',
  'latest_end_time',
  'mid_schedule_start',
  'mid_schedule_end',
  'earliest_start',
  'latest_start',
  'latest_end'
]

// 判断是否是合法的 Excel 日期数值（1970年以后）
function isExcelDate(num: number): boolean {
  return num > 25569 && num < 2958465 // 对应 1970-01-01 ~ 9999-12-31
}

// 转换 Excel 时间为 YYYY-MM-DD HH:mm:ss 格式
function excelDateToJSDate(excelDate: number): string {
  const startDate = new Date(1900, 0, 1)
  const excelDays = Math.floor(excelDate)
  const jsDate = new Date(startDate.getTime() + (excelDays - 1) * 86400000)

  const fractionalDay = excelDate - excelDays
  const totalSeconds = Math.round(fractionalDay * 86400)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  const seconds = totalSeconds % 60

  const year = jsDate.getFullYear()
  const month = String(jsDate.getMonth() + 1).padStart(2, '0')
  const day = String(jsDate.getDate()).padStart(2, '0')
  const hh = String(hours).padStart(2, '0')
  const mm = String(minutes).padStart(2, '0')
  const ss = String(seconds).padStart(2, '0')

  return `${year}-${month}-${day} ${hh}:${mm}:${ss}`
}

// 处理文件上传
const handleFileUpload = (event: Event) => {
  console.log('fields in props:', props.fields)
  const input = event.target as HTMLInputElement
  if (!input.files || input.files.length === 0) {
    ElMessage.warning('请选择一个 Excel 文件')
    return
  }

  const file = input.files[0]
  const reader = new FileReader()

  reader.onload = (e) => {
    const data = new Uint8Array(e.target?.result as ArrayBuffer)
    //console.log(data)
    const workbook = XLSX.read(data, { type: 'array' })
    const firstSheetName = workbook.SheetNames[0]
    const worksheet = workbook.Sheets[firstSheetName]

    // 解析为 JSON 数组（按行）
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 })

    // 忽略第一行标题，开始处理数据
    const result = jsonData.slice(1).map((row: any[]) => {
      const obj: Record<string, any> = {}

      props.fields.forEach((field, index) => {
        let value = row[index]

        // 如果是时间字段，并且值是合法的 Excel 日期数字，则转换
        if (dateFields.includes(field) && typeof value === 'number' && isExcelDate(value)) {
          value = excelDateToJSDate(value)
        }

        obj[field] = value ?? null
      })

      return obj
    })

    emit('import-data', result)
  }

  reader.readAsArrayBuffer(file)
  input.value = ''
}
</script>

<template>
  <div class="import-excel-container">
    <input
      type="file"
      accept=".xlsx, .xls"
      @change="handleFileUpload"
      style="display: none"
      id="excel-upload"
    />
    <label for="excel-upload" class="el-button el-button--success">导入 Excel</label>
  </div>
</template>

<style scoped>
.import-excel-container {
  display: inline-block;
}
</style>
